/*
 * @Description: 定时任务
 * @Author: DSY
 * @Date: 2022-03-19 22:45:22
 * @LastEditors: DHL
 * @LastEditTime: 2022-06-15 10:19:15
 */

import { defineComponent, computed, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { assign, cloneDeep } from 'lodash-es'
import { TwTableOptions } from '/@/types/table.d'
import { arraySerializeToStr } from '/@/utils/twUtils'

import {
  QuartzJobModel,
  QuartzJobPageParams,
  QuartzJobPageResultModel
} from '/@/api/system/model/quartzJobModel'

import {
  apiChangeStatus,
  apiQuartzJobBatchDeleteByIds,
  apiQuartzJobRunOnceJobById,
  apiQuartzJobSearch,
  apiQuartzJobUpdateById
} from '/@/api/system/quartzJob'
import quartzJobForm from './form.vue'

export default defineComponent({
  name: 'QuartzJob',
  components: { quartzJobForm },
  setup(props) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////

    const loading = ref(false)
    const loadingByDel = ref(false)

    /**
     * 表格数据
     */
    const tableData = ref()

    /**
     * 查询表单
     */
    const searchFormRef = ref()

    /**
     * 数据列表
     */
    const tableRef = ref()

    /**
     * 表单
     */
    const formRef = ref()

    /**
     * 是否有选中的行
     */
    const isSelectRows = computed(() => {
      let selectRows: Array<QuartzJobModel> = []
      if (tableRef.value) {
        selectRows = tableRef.value.getSelectRows()
      }
      return selectRows.length < 1
    })

    //////////////////////////////////////////////////
    // 查询表单
    //////////////////////////////////////////////////

    const defaultSearchForm = {
      code: '', // 任务编码
      name: '', // 任务名称
      groupName: '', // 任务分组
      invokeTarget: '', // 调用目标字符串
      cronExpression: '', // 表达式
      misfirePolicy: '', // 计划策略(0=默认,1=立即触发执行,2=触发一次执行,3=不触发立即执行)
      concurrent: '', // 并发执行（1：允许；2：禁止）
      status: '', // 状态
      remark: '' // 备注
    }

    /**
     * 查询表单
     */
    const searchForm = reactive(cloneDeep(defaultSearchForm))

    //////////////////////////////////////////////////
    // 表格
    //////////////////////////////////////////////////

    /**
     * 表格配置
     */
    const tableOptions = reactive<TwTableOptions>({
      id: 'quartzJobTable',
      sortConfig: {
        defaultSort: [{ field: 'createDate', order: 'desc' }]
      },
      columns: [
        { type: 'checkbox', fixed: 'left', title: '复选', width: 40 },
        { type: 'seq', fixed: 'left', title: '序号', width: 50 },
        { field: 'code', title: '任务编码', sortable: true, width: 150 },
        { field: 'name', title: '任务名称', sortable: true, width: 150 },
        { field: 'groupName', title: '任务分组', sortable: true, width: 100 },
        { field: 'invokeTarget', title: '调用目标字符串', sortable: true, minWidth: 200 },
        { field: 'cronExpression', title: '表达式', sortable: true, width: 100 },
        {
          field: 'misfirePolicy',
          title: '计划策略',
          sortable: true,
          width: 150,
          params: { dict: 'TWB_QUARTZ_JOB_MISFIREPOLICY' }
        },
        {
          field: 'concurrent',
          title: '并发执行',
          sortable: true,
          width: 100,
          params: { dict: 'TWB_QUARTZ_JOB_CONCURRENT' },
          slots: { default: 'concurrent' }
        },
        {
          field: 'status',
          title: '状态',
          sortable: true,
          width: 100,
          params: { dict: 'TWB_QUARTZ_JOB_STATUS' },
          slots: { default: 'status' }
        },
        { field: 'remark', title: '备注', sortable: true, width: 250 },
        { field: 'creator', title: '创建人', sortable: true, width: 150 },
        { field: 'updater', title: '更新人', sortable: true, width: 150 },
        { field: 'createDate', title: '创建时间', sortable: true, width: 150 },
        { field: 'updateDate', title: '更新时间', sortable: true, width: 150 },
        { title: '操作', fixed: 'right', width: 200, slots: { default: 'action' } }
      ]
    })

    /**
     * 绑定事件
     */
    const tableEvents = reactive({})

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 查询表格数据函数
     * @param queryParams
     */
    function searchList(queryParams: QuartzJobPageParams) {
      loading.value = true
      apiQuartzJobSearch(assign(queryParams, searchForm))
        .then((result: QuartzJobPageResultModel) => {
          tableData.value = result
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 查询表格数据
     */
    function handleSearch() {
      tableRef.value.handleQuery()
    }

    /**
     * 刷新
     */
    function handleRefresh() {
      tableRef.value.handleReload()
    }

    /**
     * 重置
     */
    function handleReset() {
      assign(searchForm, cloneDeep(defaultSearchForm))
      tableRef.value.handleQuery()
    }

    /**
     * 批量删除
     */
    function handleDelete(row?: QuartzJobModel) {
      let selectRows: Array<QuartzJobModel> = []

      if (row) {
        selectRows = [row]
      } else {
        selectRows = tableRef.value.getSelectRows()
      }

      ElMessageBox.confirm(`此操作将删除${selectRows.length}条记录, 是否继续?`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          loadingByDel.value = true
          const ids = arraySerializeToStr(selectRows, 'id')
          apiQuartzJobBatchDeleteByIds(ids)
            .then((result) => {
              if (result?.success) {
                handleRefresh()

                ElMessage.success(result.message)
              } else {
                ElMessage.error(result?.message)
              }
            })
            .catch(() => { })
            .finally(() => {
              loadingByDel.value = false
            })
        })
        .catch(() => {
          ElMessage.info('删除被取消了')
        })
    }

    /**
     * 弹出表单
     */
    function handleOpenForm(action: string, row?: QuartzJobModel) {
      formRef.value.handleOpen(action, row)
    }

    /**
     * 根据主键更新
     */
    function handleUpdateById(row: QuartzJobModel) {
      loading.value = true

      apiQuartzJobUpdateById(row)
        .then((result) => {
          if (result?.success) {
            // 刷新表格数据
            handleRefresh()

            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 根据主键更新
     */
    function handleChangeStatus(row: QuartzJobModel) {
      loading.value = true
      const id: string = row.id as string
      const status: string = row.status as string
      apiChangeStatus(id,status)
          .then((result) => {
            if (result?.success) {
              // 刷新表格数据
              handleRefresh()

              ElMessage.success(result.message)
            } else {
              ElMessage.error(result?.message)
            }
          })
          .catch(() => { })
          .finally(() => {
            loading.value = false
          })
    }

    /**
     * 立即执行一次
     * @param row
     */
    function handleRunOnceJob(row: QuartzJobModel) {
      loading.value = true

      const id: string = row.id as string
      apiQuartzJobRunOnceJobById(id)
        .then((result) => {
          if (result?.success) {
            // 刷新表格数据
            handleRefresh()

            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }
    return {
      loading,
      loadingByDel,
      tableData,
      searchFormRef,
      tableRef,
      formRef,
      searchForm,
      tableOptions,
      tableEvents,
      isSelectRows,
      searchList,
      handleSearch,
      handleRefresh,
      handleReset,
      handleDelete,
      handleOpenForm,
      handleUpdateById,
      handleRunOnceJob,
      handleChangeStatus
    }
  }
})
